<template>
  <el-container>
    <el-dialog
      :title="isAdd ? '用户添加' : '用户编辑'"
      :visible.sync="centerDialogVisible"
      @closed="closeDialog()"
      width="70%"
      height="60%"
      :close-on-click-modal="false"
      center
    >
      <el-form
        ref="userForm"
        :model="userForm"
        label-width="150px"
        fullscreenLoading
        :rules="userFormRules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户编号">
              <el-input
                v-model.trim="userForm.id"
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="用户头像">
              <el-upload
                v-if="!isAdd"
                style="margin-left: 15%"
                :headers="headers"
                class="avatar-uploader"
                action="http://localhost:8001/ems/admin/upload/avatar"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-avatar
                  v-if="!isAdd"
                  shape="square"
                  :size="50"
                  fit="fill "
                  alt="头像"
                  :src="prefixUrl + '/' + userForm.avatar"
                  style="margin-left: 15%"
                ></el-avatar>
                <!-- <img
                  v-if="!isAdd"
                  :src="prefixUrl + '/' + userForm.avatar"
                  class="avatar"
                /> -->
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-avatar
                v-else
                shape="square"
                :size="50"
                fit="fill "
                alt="头像"
                :src="prefixUrl + '/' + userForm.avatar"
                style="margin-left: 15%"
              ></el-avatar> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="名称">
              <el-input
                v-model="userForm.name"
                placeholder="请输入名称"
                class="inputWdith"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="账号" prop="title">
              <el-input
                v-model="userForm.username"
                placeholder="请输入账号"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="用户密码">
              <el-input
                v-model="userForm.password"
                placeholder="用户密码"
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="用户类型">
              <el-input
                v-model="userForm.description"
                placeholder="用户类型"
                disabled
              ></el-input> </el-form-item
          ></el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-switch
                v-model="userForm.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="0"
                :inactive-value="1"
                validate-event
              >
              </el-switch> </el-form-item
          ></el-col>
          <el-col :span="24">
            <div>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="submitForm('userForm')"
                  v-loading.fullscreen.lock="fullscreenLoading"
                  >确认</el-button
                >
                <el-button @click="resetForm('userForm')" v-show="isAdd"
                  >重置</el-button
                >
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <el-container>
      <el-main>
        <el-row class="function-button">
          <!-- <el-button type="primary" size="small" round @click="handleAdd()"
            >新增根用户</el-button
          > -->
          <el-button type="success" size="small" round @click="refresh()"
            >刷新按钮</el-button
          >
          <el-input
            style="width: 20%; margin-left: 40px"
            placeholder="输入用户名称"
            size="samll"
            prefix-icon="el-icon-search"
            v-model="userQueryParam.name"
          >
          </el-input>
          <el-select
            v-model="userQueryParam.roleId"
            placeholder="用户类型"
            filterable
            clearable
            style="width: 20%; margin-left: 40px"
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.description"
              :value="item.id"
            ></el-option>
          </el-select>

          <el-button round style="margin-left: 10px" @click="queryByCondition"
            >查询</el-button
          >
        </el-row>
        <template>
          <el-table
            ref="userTable"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            v-loading="loading"
            :data="userList"
            fit
            border
            max-height="700"
            size="medium "
            highlight-current-row
            row-key="id"
            tooltip-effect="dark"
          >
            <el-table-column prop="id" label="用户编号"> </el-table-column>
            <el-table-column prop="name" label="用户名称"> </el-table-column>
            <el-table-column prop="username" label="用户账号">
            </el-table-column>
            <el-table-column prop="avatar" label="用户头像">
              <template slot-scope="scope">
                <el-avatar
                  shape="square"
                  :size="50"
                  fit="fill "
                  alt="头像"
                  :src="prefixUrl + '/' + scope.row.avatar"
                  style="margin-left: 15%"
                ></el-avatar>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="用户类型">
            </el-table-column>
            <el-table-column prop="state" label="状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.state"
                  disabled
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  :active-value="0"
                  :inactive-value="1"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click.stop="handEdit(scope.row)"
                  size="small"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  @click.stop="handDel(scope.row)"
                  size="small"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { getUserList, doEditUser, delUser } from '@/api/user';
import { getToken } from '@/utils/auth';
import { mapGetters } from 'vuex';
import throttle from 'lodash/throttle'; //
import { Message } from 'element-ui';
export default {
  name: 'UserMng',
  data() {
    return {
      prefixUrl: process.env.VUE_APP_BASE_API,
      isAdd: false,
      fullscreenLoading: false,
      loading: false,
      centerDialogVisible: false,
      condition: {},
      currentPage: 1,
      pageSize: 10,
      total: 0,
      imageUrl: '',
      userList: [],
      userForm: { avatar: '' },
      userQueryParam: {},
      headers: {
        'X-Token': getToken(),
      },
      userFormRules: {
        name: [
          {
            required: true,
            message: '用户名称不能为空',
            trigger: 'blur',
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters('RoleMng', ['roleList']),
  },
  mounted() {
    this.loading = true;
    // 查询用户列表
    this.getUserList();
    // 获取角色列表
    this.getAllRoleList();
  },
  methods: {
    handDel(row) {
      let result;
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
      })
        .then(async () => {
          delUser(row.id).then((res) => {
            this.$message({
              message: res.message,
              type: 'success',
              duration: 2 * 1000,
            });
            this.getUserList();
          });
        })
        .catch(() => {
          this.$message({
            message: '取消删除',
            type: 'info',
            duration: 2 * 1000,
          });
        });
    },

    // 刷新用户列表
    refresh: throttle(async function () {
      this.loading = true;
      this.currentPage = 1;
      await this.getUserList();
      this.$message({
        message: '刷新成功',
        type: 'success',
        duration: 1 * 1000,
      });
    }, 800),

    // 对话框关闭前的回调
    closeDialog() {
      this.isAdd = false;
    },

    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.getUserList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUserList();
    },

    // 获取角色列表
    getAllRoleList() {
      this.$store.dispatch('RoleMng/getAllRoleList');
    },
    // 重置表单判定状态
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 编辑用户
    handEdit(row) {
      this.resetForm.avatar = '';
      if (row.avatar) {
        this.resetForm.avatar = row.avatar;
      }
      if (this.$refs.userForm) {
        this.resetForm('userForm');
      }
      this.centerDialogVisible = true;
      this.userForm = row;
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.userForm.avatar = res.data.fileName;
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/png/jpeg 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    // 表单提交
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.fullscreenLoading = true;
          try {
            // 接收返回的结果
            let result = {};
            if (this.isAdd) {
              let paramsArray = [];
              UserMng;
              let params = {
                ...this.userForm,
              };
              paramsArray.push(params);
              // 发送请求
              result = await this.$store.dispatch(
                'UserMng/batchAddUser',
                paramsArray
              );
            } else {
              doEditUser(this.userForm).then((res) => {
                this.$message({
                  message: result.message,
                  type: 'success',
                  duration: 2 * 1000,
                });
                this.fullscreenLoading = false; // 关闭遮罩层
                this.isAdd = false; // 重置表单状态
                this.centerDialogVisible = false;
              });
            }
          } catch (error) {
            Message.error(error || 'Has Error');
          }
        } else {
          return false;
        }
      });
    },

    // 条件查询
    async queryByCondition() {
      // 初始化条件查询参数
      this.condition = {
        ...this.userQueryParam,
      };
      await this.getUserList();
      this.$nextTick(() => {
        this.$message({
          message: '查询成功',
          type: 'success',
          duration: 1 * 1000,
        });
      });
    },

    // 查询用户列表
    getUserList() {
      let params = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        condition: this.condition || {},
      };
      getUserList(params).then((res) => {
        this.loading = false;
        this.userList = res.data.userListIPage.records;
        this.currentPage = res.data.userListIPage.currentPage;
        this.pageSize = res.data.userListIPage.pageSize;
        this.total = res.data.userListIPage.total;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.block {
  text-align: center;
}
</style>
